<?php
declare(strict_types=1);

namespace Modules\TeacherLesson\Http\Controllers;

use Catch\Base\CatchController as Controller;
use Catch\Exceptions\FailedException;
use Modules\Configuration\Models\Configuration;
use Modules\LessonHour\Http\Controllers\LessonHourController;
use Modules\LessonTime\Models\LessonTime;
use Modules\Reservation\Models\Reservation;
use Modules\TeacherLesson\Models\TeacherLesson;
use Illuminate\Http\Request;


class TeacherLessonController extends Controller
{
    public function __construct(
        protected readonly TeacherLesson $model
    ){}

    public function index(Request $request): mixed
    {
        $startDate = $request->get('start_time');
        $startDate = empty($startDate) ? date('Y-m-d') : $startDate;
        $endDate = $request->get('end_time');
        $endDate = empty($endDate) ? date('Y-m-d', strtotime($startDate . " +7 day")) : $endDate;
        $timeLong = empty($endDate)  ? 7 : (strtotime($endDate) - strtotime($startDate)) / 86400;

        $user = $this->getLoginUser();
        $user['id'] = 8;
        $result = [];

        $reservation = Reservation::query()
            ->whereBetween('reservation.lesson_date', [$startDate, $endDate])
            ->where('reservation.teacher_id', $user['id'])
            ->whereIn('reservation.status', [LessonHourController::RESERVATION_1,LessonHourController::RESERVATION_2,LessonHourController::RESERVATION_4])
            ->select(['customer.username as customer_name','subject.name as subject_name','grade.name as grade_name','reservation.status','reservation.lesson_date','reservation.lesson_time_id','reservation.id as reservation_id'])
            ->join('customer', 'customer.id', '=', 'reservation.customer_id')
            ->join('subject', 'subject.id', '=', 'reservation.subject_id')
            ->join('grade', 'grade.id', '=', 'subject.grade_id')
            ->get();

        $reservation = $this->getKeyArr($reservation);

        for ($i = 0; $i < $timeLong; $i++)
        {
            $date = date('Y-m-d', strtotime($startDate . " +$i day"));
            $lessonTimeIds = $this->getDateTimeIds($this->getLoginUser(), $date);
            $result[$i]['date'] = $date;
            $result[$i]['week'] = date("w",strtotime($date)) == 0 ? "周日" : $this->translateWeek(date("w",strtotime($date)));

            foreach ($lessonTimeIds as $lessonTimeId)
            {
                if (isset($reservation[$date . "_" . $lessonTimeId]))
                {
                    $result[$i]['time'][] = $reservation[$date . "_" . $lessonTimeId];
                }
            }
        }

        return $result;
    }

    public function update(Request $request): mixed
    {
        $date = $request->get('date');
        $user = $this->getLoginUser();
        $time = $request->get('time_ids');
        if(empty($date)) throw new \Exception('date is required');

        $newIds = explode(',', $time);
        $oriIds = $this->getDateTimeIds($user, $date);

        // 获取删除的时间
        $delIds = array_values(array_diff($oriIds, $newIds));

        // 判断删除的时间有没有预约记录
        $existTime = [];
        foreach ($delIds as $id)
        {
            $reservation = Reservation::query()->where('lesson_time_id', $id)->where('lesson_date', $date)->first();
            if ($reservation)
            {
                $existTime[] = "[".$reservation->lesson_time->start_time . '~' . $reservation->lesson_time->end_time. "]";
            }
        }

        if (!empty($existTime))
        {
            throw new FailedException("时间段" . implode(',', $existTime) . "已有预约记录，不能删除");
        }

        $teacherLesson = TeacherLesson::query()->where(['lesson_date'=>$date,'teacher_id'=>$user['id']])->first();

        // 更新老师课程时间
        $teacherLesson['lesson_date'] = $date;
        $teacherLesson['lesson_time_ids'] = implode(',', $newIds);
        $teacherLesson['teacher_id'] = $user['id'];

        if (isset($teacherLesson['id']))
        {
            return $teacherLesson->save();
        }
        else
        {
            return $this->model->createBy($teacherLesson);
        }
    }

    public function detail(Request $request): mixed
    {
        $date = $request->get('date');
        $user = $this->getLoginUser();

        if (empty($date))
        {
            throw new FailedException("请选择日期");
        }

        $lessonTimeIds = $this->getDateTimeIds($user, $date);

        // 转int
        $lessonTimeIds = array_map(function($id){
            return (int)$id;
        }, $lessonTimeIds);

        return ["time_ids" => $lessonTimeIds];
    }

    /**
     * 获取老师课程时间
     *
     * @param array $user
     * @param $date
     * @return array
     */
    public function getDateTimeIds($user = [], $date)
    {
        $lessonTimeArr = LessonTime::query()->select(['id','start_time','end_time','time_long'])->get();
        $teacherLesson = TeacherLesson::query()->where(['lesson_date'=>$date,'teacher_id'=>$user['id']])->first();
        $lessonConfigs = Configuration::query()->select("time_ids")->where('id', '1')->first();

        return isset($teacherLesson['lesson_time_ids']) ? explode(',', $teacherLesson['lesson_time_ids']) : (isset($lessonConfigs['time_ids']) ? explode(',', $lessonConfigs['time_ids']) : array_keys($lessonTimeArr));
    }


    public function getKeyArr($data)
    {
        $result = [];
        foreach ($data as $item)
        {
            $keys = $item['lesson_date']."_".$item['lesson_time_id'];
            $result[$keys] = [
                'id' => $item['lesson_time_id'],
                'customer_name' => $item['customer_name'],
                'subject_name' => $item['grade_name'] . "-" . $item['subject_name'],
                'status' => $item['status'],
                'reservation_id' => $item['reservation_id'],
            ];
        }
        return $result;
    }

    public function translateWeek($week)
    {
        return $week == 1 ? "周一" : ($week == 2 ? "周二" : ($week == 3 ? "周三" : ($week == 4 ? "周四" : ($week == 5 ? "周五" : ($week == 6 ? "周六" : "周日")))));
    }
}
